import HttpRequestInterface from "../HttpRequestInterface";

export default class WebRequest extends HttpRequestInterface {
  request(url, method = 'POST', data = null, options = null) {
    options = options || {};

    function fn(data) {
      //空实现, 用来填充未设置的回调
    }

    let success = options.onSuccess || fn;
    let failure = options.onFail || fn;

    method = method.toUpperCase();

    let dataArray = [];
    if (data) {
      for (let name in data) {
        if (data.hasOwnProperty(name)) {
          let tmp = name + "=" + encodeURIComponent(data[name]);
          dataArray.push(tmp);
        }
      }
    }
    //将data拼接成字符串
    let dataString = dataArray.join('&');
    if (method === 'GET' && data) {
      url += (url.indexOf('?') === -1 ? '?' : '&') + dataString;
      data = null;
      dataString = null;
    }
    // @ts-ignore
    let xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');
    xhr.timeout = 5000;
    xhr.ontimeout = function (event) {
      console.log("WebRequest超时:" + url);
      failure('WebRequest time out');
    };
    xhr.onreadystatechange = function () {
      if (xhr.readyState === 4) {
        let s = xhr.status;
        if (s >= 200 && s < 300) {
          success(xhr.responseText);
        } else {
          console.log("WebRequest异常:" + url + ", status:" + xhr.status);
          failure(xhr.statusText);
        }
      } else {
      }
    };
    xhr.open(method, url);
    if (method === 'POST') {
      xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded;');
    }
    xhr.send(dataString);
    return xhr;
  }


  post(url, data = null, options = null) {
    this.request(url, "POST", data, options);
  }

  postJson(url, data = null, options = null) {
    options = options || {};
    let {onSuccess, onFail} = options;
    let newOptions = Object.assign({}, options, {
      onSuccess: (responseText) => {
        try {
          onSuccess && onSuccess(JSON.parse(responseText));
        } catch (e) {
          onFail && onFail(e.toString());
        }
      }
    });
    this.post(url, data, newOptions);
  }

  getJson(url, data = null, options = null) {
    options = options || {};
    let {onSuccess, onFail} = options;
    let newOptions = Object.assign({}, options, {
      onSuccess: (responseText) => {
        try {
          onSuccess && onSuccess(JSON.parse(responseText));
        } catch (e) {
          onFail && onFail(e.toString());
        }
      }
    });
    this.request(url, "GET", data, newOptions);
  }

}
